package com.gao.weblog.common.domain.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gao.weblog.common.config.InsertBatchMapper;
import com.gao.weblog.common.domain.dos.ArticleTagRelDO;
import com.gao.weblog.common.domain.dos.TagDO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.stream.Collectors;

public interface ArticleTagRelMapper extends InsertBatchMapper<ArticleTagRelDO> {
    default int deleteByArticleId(Long articleId) {

        return delete(Wrappers.<ArticleTagRelDO>lambdaQuery()
                .eq(ArticleTagRelDO::getArticleId, articleId));
    }

    default List<Long> selectByArticleId(Long articleId){
        LambdaQueryWrapper<ArticleTagRelDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleTagRelDO::getArticleId, articleId);
        List<ArticleTagRelDO> articleTagRelDOS = selectList(wrapper);
        return articleTagRelDOS.stream().map(ArticleTagRelDO::getTagId).collect(Collectors.toList());
    }

    default List<ArticleTagRelDO> selectByArticleIds(List<Long> articleIds){
        return selectList(Wrappers.<ArticleTagRelDO>lambdaQuery()
                .in(ArticleTagRelDO::getArticleId, articleIds));
    }

    default List<ArticleTagRelDO> selectByTagId(Long tagId) {
        return selectList(Wrappers.<ArticleTagRelDO>lambdaQuery()
                .eq(ArticleTagRelDO::getTagId, tagId));
    }

    @Select("SELECT t.* " +
            "FROM weblog.t_tag t " +
            "JOIN weblog.t_article_tag_rel rel ON rel.tag_id = t.id " +
            "WHERE rel.article_id = #{articleId}")
    List<TagDO> selectTagsByArticleId(@Param("articleId") Long articleId);
}
